﻿using UnityEngine;
using System.Collections;

public class ActiveBarrierController : MonoBehaviour {
	
	private UISlider slider;
	private UILocalize loc;
	
	private bool built = false;
	
	// Use this for initialization
	void Start () {
		GetComponent<UIForwardEvents>().target = transform.parent.gameObject;
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void Awake()
	{
		slider = GetComponentInChildren<UISlider>();
		loc = GetComponentInChildren<UILocalize>();
	}
	
	public IEnumerator Build(float buildTime)
	{
		while(slider.value < 1)
		{
			slider.value += (Time.deltaTime / buildTime);
			yield return null;
		}
		buildFinished();
	}
	
	private void buildFinished()
	{
		slider.value = 1;
		loc.key = "Barrier";
		loc.Localize();
		
		built = true;
		collider.enabled = true;
	}
	
	public void HitByEnemy(EnemyController enemy)
	{
		if(!built)
		{
			return;
		}
		
		StartCoroutine(enemy.Kill());
		
		StartCoroutine(RemoveBarrier());
	}
	
	IEnumerator RemoveBarrier()
	{
		TweenScale.Begin(gameObject, 0.2f, Vector3.zero);
		transform.parent.SendMessage("BarrierRemoved");
		
		yield return new WaitForSeconds(0.2f);
		
		Destroy(gameObject);
	}
	
	
}
